package com.xyhuo.leetcode.december;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 简化路径
 * https://leetcode.cn/problems/simplify-path/
 *
 * @time 2023/12/27
 */
public class SimplifyPath {

//    public static void main(String[] args) {
//        SimplifyPath sp = new SimplifyPath();
//        String s = sp.simplifyPath("/a//b////c/d//././/..");
//        System.out.println(s);
//    }

    public String simplifyPath(String path) {
        if (!path.endsWith("/")) {
            path += "/";
        }
        char[] charArray = path.toCharArray();
        int index = 0;
        String last = "../";
        String cur = "./";
        char x = '/';
        Deque<String> deque = new ArrayDeque<>();
        while (index < charArray.length) {
            while (index < charArray.length && charArray[index] == x) {
                index++;
            }

            if (index + 2 < charArray.length) {
                String tmp = path.substring(index, index + 3);
                if (tmp.equals(last)) {
                    if (!deque.isEmpty()) {
                        deque.removeLast();
                    }
                    index += 3;
                    continue;
                }
            }
            if (index + 1 < charArray.length) {
                String tmp = path.substring(index, index + 2);
                if (tmp.equals(cur)) {
                    index += 2;
                    continue;
                }
            }
            if (index >= charArray.length - 1) {
                break;
            }
            int startIndex = index;
            while (index < charArray.length && charArray[index] != '/') {
                index++;
            }
            String val = path.substring(startIndex, index);
            deque.addLast(val);
        }

        StringBuilder sb = new StringBuilder();

        if (deque.isEmpty()) {
            sb.append("/");
        }
        while (!deque.isEmpty()) {
            sb.append("/");
            sb.append(deque.removeFirst());
        }
        return sb.toString();
    }
}
